//
//  ViewController.swift
//  SwiftSample
//
//  Created by zhou shadow on 5/6/15.
//  Copyright (c) 2015 Honeywell Inc. All rights reserved.
//

import UIKit
import SVProgressHUD
protocol CaptuvoDecoderManagerDelegate:NSObjectProtocol {
    func finishCapScan(_ msg: String?)
}

class CaptuvoDecoderManager: NSObject,CaptuvoEventsProtocol{
    var successItems: Int = 0
    var batteryStatus:ProtocolConnectionStatus = ProtocolConnectionStatus(rawValue: 5)
    var status: ProtocolConnectionStatus {
        get{
            return batteryStatus
        }
        set{
            if newValue != batteryStatus {
                switch newValue.rawValue {
                case 0: // 正确连接
//                    SVProgressHUD.showSuccessWithStatus("扫码器开启")
                    batteryStatus = newValue
                    captuvoIsOn = true
                case 1: // 正确连接
//                    SVProgressHUD.showSuccessWithStatus("扫码器已开启")
                    batteryStatus = newValue
                    captuvoIsOn = true
                case 2: //电量低
                    SVProgressHUD.showSuccess(withStatus: "扫码器电量不足，连接失败")
                    batteryStatus = newValue
                    captuvoIsOn = false
                case 5: //无设备
//                    SVProgressHUD.showErrorWithStatus("扫码器连接断开")
                    batteryStatus = newValue
                    captuvoIsOn = false
                default: //扫码器未知错误
                    captuvoIsOn = false
                    let alertVC = UIAlertController(title: "关闭应用提醒", message: "扫描器已断开，连接扫码器需重启应用", preferredStyle: UIAlertControllerStyle.alert)
                    alertVC.addAction(UIAlertAction(title: "稍后手动重启", style: UIAlertActionStyle.default, handler: nil))
                    alertVC.addAction(UIAlertAction(title: "立即关闭应用", style: UIAlertActionStyle.default, handler: { (UIAlertAction) in
                        UIApplication.shared.delegate?.applicationWillResignActive!(UIApplication.shared)
                       exit(0)
                    }))
                    UIApplication.shared.keyWindow?.rootViewController?.present(alertVC, animated: true, completion: nil)
//                    SVProgressHUD.showWithStatus("重启扫码器……")
//                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, __int64_t(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), {
//                        Captuvo.sharedCaptuvoDevice().forceBatteryLowShutdown()
//                    })
//                    Captuvo.sharedCaptuvoDevice().stopDecoderHardware()
//                    Captuvo.sharedCaptuvoDevice().stopPMHardware()
//                    let manager = CaptuvoDecoderManager.shareCaptuvoDecoderManager
//                    Captuvo.sharedCaptuvoDevice().removeCaptuvoDelegate(manager)
//                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, __int64_t(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), {
//                        SVProgressHUD.dismiss()
//                        CaptuvoDecoderManager.shareCaptuvoDecoderManager = CaptuvoDecoderManager()
//                        Captuvo.sharedCaptuvoDevice().addCaptuvoDelegate(CaptuvoDecoderManager.shareCaptuvoDecoderManager)
//                        CaptuvoDecoderManager.shareCaptuvoDecoderManager.captuvoConnected()
//                    })
                }
            }

//            if newValue == ProtocolConnectionStatus(rawValue: 3) || newValue == ProtocolConnectionStatus(rawValue: 4) ||  newValue == ProtocolConnectionStatus(rawValue: 0){
//                SVProgressHUD.showWithStatus("扫码器连接错误，正重启……")
//                dispatch_after(NSEC_PER_SEC * 2, dispatch_get_main_queue(), {
//                    Captuvo.sharedCaptuvoDevice().forceBatteryLowShutdown()
//                })
//                dispatch_after(NSEC_PER_SEC * 4, dispatch_get_main_queue(), {
//                    
//                    self.captuvoConnected()
//                })
//            }
//            if newValue != batteryStatus{
//                captuvoIsOn = CaptuvoDecoderManager.statusHander(newValue)
//                batteryStatus = newValue
//            }
        }
    }
    weak var activeTextfield:UITextField?
    weak var delegate:inputViewProtocol?
    weak var inputDelegate:CaptuvoDecoderManagerDelegate?
    static let shareCaptuvoDecoderManager:CaptuvoDecoderManager = {
        let manager = CaptuvoDecoderManager()
        Captuvo.sharedCaptuvoDevice().addDelegate(manager)
        Captuvo.sharedCaptuvoDevice().startDecoderHardware()
        Captuvo.sharedCaptuvoDevice().setMSRTrackSelection(TrackSelectionRequire1and2)
        manager.status = Captuvo.sharedCaptuvoDevice().startPMHardware()
        return manager
    }()
    
    override init() {
        super.init()
        self.setUPConfig()
    }
    

    func setUPConfig() {
         NotificationCenter.default.addObserver(self, selector: #selector(CaptuvoDecoderManager.newEnditingBegin(_:)), name: NSNotification.Name.UITextFieldTextDidBeginEditing, object: nil)
    }
    
    func newEnditingBegin(_ notification: Notification){
        let object:UITextField = (notification.object as? UITextField)!
        self.activeTextfield = object
    }
    
    func decoderDataReceived(_ data: String!) {
        if let textfield = self.activeTextfield{
            //添加逻辑，只保留数字、字母、其他可见的字符
            let characters = data.characters
            var result = ""
            for char in characters {
                if char > "!" && char < "~"{
                    result += "\(char)"
                }
            }
            textfield.text = result
            if let delegate = self.delegate {
                delegate.finishInput(result)
            }
            if let delegate = self.inputDelegate{
                delegate.finishCapScan(result)
            }
        }
    }
    
    func msrStringDataReceived(_ data: String!, validData status: Bool) {
//        msrlbl.text = data
        SVProgressHUD.showSuccess(withStatus: data)
    }
    
    func pmReady(){
//        batterlbl.text = "Battery is Ready"
    }
    
    func msrReady() {
//        msrlbl.text = "MSR is Ready"
//         SVProgressHUD.showSuccessWithStatus("MSR is Ready")
    }
    
    func decoderReady() {
//        barcodelbl.text = "Scanner is Ready"
//        SVProgressHUD.showSuccessWithStatus("Scanner is Ready")
       
    }
    
    private func responseBatteryDetailInformation(_ batteryInfo:cupertinoBatteryDetailInfo)
    {
//        batterlbl.text="Battery: \(batteryInfo.percentage) %";
        SVProgressHUD.showSuccess(withStatus: "Battery: \(batteryInfo.percentage) %")
    }
    
    func captuvoConnected(){
//        let manager = CaptuvoDecoderManager.shareCaptuvoDecoderManager
//        Captuvo.sharedCaptuvoDevice().addCaptuvoDelegate(manager)
        Captuvo.sharedCaptuvoDevice().startDecoderHardware()
        Captuvo.sharedCaptuvoDevice().setMSRTrackSelection(TrackSelectionRequire1and2)
        status = Captuvo.sharedCaptuvoDevice().startPMHardware()
    }
    
    func captuvoDisconnected()
    {
//        let manager = CaptuvoDecoderManager.shareCaptuvoDecoderManager
//        Captuvo.sharedCaptuvoDevice().removeCaptuvoDelegate(manager)
        Captuvo.sharedCaptuvoDevice().stopDecoderHardware()
        Captuvo.sharedCaptuvoDevice().stopPMHardware()
        status = ProtocolConnectionStatus(rawValue: 5)
    }
    
}

